package com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.service.UserService;

/****
 * 配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	/****
	 * 该类实现UserDetailsServer接口，重写loadUserByUsername方法，从数据库获取用户名，密码，角色
	 */
    @Autowired
    UserService userService;

    /*****
     * 
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    	//可以从数据库中得到一些信息
        auth.userDetailsService(userService);
    }

    /****
            * 设置加密方式
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    
    /****
     * 访问权限控制
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    	  http.authorizeRequests()
          .antMatchers("/dba/**").hasRole("dba")
          .antMatchers("/admin/**").hasRole("admin")
          .antMatchers("/user/**").hasRole("user")
          .anyRequest().authenticated()
          .and()
          .formLogin()
          .permitAll()
          .and()
          .csrf().disable();
    }
}
